package com.example.demo.service.impl;

import com.example.demo.service.AiApiService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.codehaus.jettison.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AiApiServiceImpl implements AiApiService {
    int count=0;
    List<Map<String, String>> msg = new ArrayList<>();
    private final ObjectMapper objectMapper;

    @Value("${kimi.api.key}")
    private String apiKey;

    @Value("${kimi.api.url}")
    private String apiUrl;

    private final RestTemplate restTemplate;

    public AiApiServiceImpl(ObjectMapper objectMapper, RestTemplate restTemplate) {
        this.objectMapper = objectMapper;
        this.restTemplate = restTemplate;
    }

    public String getKimiResponse(String model, String prompt) throws JsonProcessingException {
        msg.add(Map.of("role", "system", "content", "你是智能工程助手。"));
        msg.add(Map.of("role", "user", "content", prompt));
        //text=text+prompt;
        String url = apiUrl + "/chat/completions";
        HashMap<String, Object> request = new HashMap<>();
        request.put("model", model);
        request.put("messages", msg);
        request.put("temperature", 0.3);
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer " + apiKey);
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<HashMap<String, Object>> entity = new HttpEntity<>(request, headers);

        ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);
        String responseBody = response.getBody();
        String ans =objectMapper.readTree(responseBody).path("choices").get(0).path("message").path("content").asText();
        if(ans != null && !ans.isEmpty()) {msg.add(Map.of("role", "assistant", "content", ans));}
        count++;
        if (msg.size()>5) {
            msg.remove(0);
        }
        return response.getBody();
    }



    public String reviewCode(List<MultipartFile> files) throws IOException {
        String url = apiUrl + "/chat/completions";
        String s = "";
        // 创建HTTP头信息
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer " + apiKey);
        msg.add(Map.of("role", "system", "content", "你是智能工程助手。"));
        for (MultipartFile file : files) {
            s = new String(file.getBytes());
            msg.add(Map.of("role",  "system", "content", s));
        }
        HashMap<String, Object> request = new HashMap<>();
        request.put("model", "moonshot-v1-128k");
        request.put("temperature", 0.3);

        msg.add(Map.of("role", "user", "content", "将收到数据作为一个项目进行分析总结并指出问题，提出建议。"));
        request.put("messages", msg);
        // 创建HttpEntity对象
        HttpEntity<HashMap<String, Object>> entity = new HttpEntity<>(request, headers);
        // 创建RestTemplate实例
        RestTemplate restTemplate = new RestTemplate();
        // 发送POST请求并接收响应
        ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);
        // 处理响应
        return response.getBody();
    }

    @Override
    public String getTyResponse(String question,int type) throws JsonProcessingException {
        String url ="https://gpt.api.zhangyichi.cn/v1/chat/completions";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer " + "sk-sxkl094J9MmGf1kT3bgunCagI1s0DtG3C4t6CIBBI5fKfupH");
        HashMap<String, Object> request = new HashMap<>();
        request.put("model","gpt-4o-mini");
        msg.add(Map.of("role", "system", "content", "你是智能工程助手。"));
        if(type==2) msg.add(Map.of("role", "user", "content", "将收到数据作为一个项目进行分析总结并指出问题，提出建议。"));
        if (type==1) msg.add(Map.of("role", "system", "content", "请将收到数据作为一个项目按阿里Java标准进行代码审查并分析总结之后指出问题，提出建议。"));
        msg.add(Map.of("role", "user", "content", question));
        request.put("messages", msg);
        request.put("temperature", 0.3);
        request.put("stream",false);
        HttpEntity<HashMap<String, Object>> entity = new HttpEntity<>(request, headers);
        ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);
        String ans = objectMapper.readTree(response.getBody()).path("choices").get(0).path("message").path("content").asText();
        if(type!=0)msg.clear();
        if (msg.size()>20) {
            for (int i = 0; i < 5; i++) {
                msg.remove(0);
            }
        }
       if(type!=0){ return ans;}
       else {
           return response.getBody();
       }
    }



    @Override
    public String getTy(MultipartFile[] files) throws IOException {
        String url ="https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer " + "sk-69cbffe1abc14cd49eff6351b0bd98b0");
        HashMap<String, Object> request = new HashMap<>();
        request.put("model","qwen-plus");
        msg.add(Map.of("role", "system", "content", "你是智能工程助手。"));
        for (MultipartFile file : files) {
            String s = new String(file.getBytes());
            msg.add(Map.of("role",  "system", "content", s));
        }
        request.put("messages", msg);
        request.put("temperature", 0.3);
        request.put("stream",false);
        HttpEntity<HashMap<String, Object>> entity = new HttpEntity<>(request, headers);
        ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);
        return response.getBody();
    }

    @Override
    public String geths(String question) {
        String url ="ark.cn-beijing.volces.com";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer " + "Tm1OaE1qSm1NR0k1TkRkaE5EQm1ZV0ZsTVdVNE1EZzJNVGt6T0RVNFptWQ==");
        HashMap<String, Object> request = new HashMap<>();
        request.put("model","qwen-plus");
        msg.add(Map.of("role", "system", "content", "你是智能工程助手。"));
        msg.add(Map.of("role", "system", "content", "请将收到数据作为一个项目进行分析总结并指出问题，提出建议。"));
        msg.add(Map.of("role", "user", "content", question));
        request.put("messages", msg);
        request.put("temperature", 0.3);
        request.put("stream",true);
        HttpEntity<HashMap<String, Object>> entity = new HttpEntity<>(request, headers);
        ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);
        return response.getBody();
    }

    @Override
    public String getgpt(String question) {
        String url ="https://gpt.api.zhangyichi.cn/v1/chat/completions";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer " + "sk-sxkl094J9MmGf1kT3bgunCagI1s0DtG3C4t6CIBBI5fKfupH");
        HashMap<String, Object> request = new HashMap<>();
        request.put("model","gpt-4o-mini");
        msg.add(Map.of("role", "system", "content", "你是智能工程助手。"));
        msg.add(Map.of("role", "user", "content", question));
        request.put("messages", msg);
        request.put("temperature", 0.3);
        //request.put("stream",false);
        HttpEntity<HashMap<String, Object>> entity = new HttpEntity<>(request, headers);
        ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);
        return response.getBody();
    }



}